package com.lxblyw.web;


import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.lxblyw.entity.Contact;
import com.lxblyw.entity.ContactNote;
import com.lxblyw.entity.EmployeeProject;
import com.lxblyw.service.ContactNoteSevice;
import com.lxblyw.service.ContactService;
import com.lxblyw.util.Const;
import com.lxblyw.util.DateUtil;
import com.lxblyw.util.PKUtil;


public class ContactNoteServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		
		String method = request.getParameter("_m");
		
		if("showedit".equals(method)) {
			showEditContactNote(request,response);
		} else if("savenote".equals(method)) {
			saveNote(request,response);
		} else if("".equals(method) || method == null) {
			list(request,response);
		}
	}

	private void list(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException{
		HttpSession session = request.getSession();
		
		String contactid = request.getParameter("contactid");
		
		List<ContactNote> cnList = new ContactNoteSevice().findAllContent(contactid);
		
		session.setAttribute("cnList", cnList);
		
		request.getRequestDispatcher("WEB-INF/views/contact_note.jsp").forward(request, response);
	}

	private void saveNote(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
		String content = request.getParameter("content");
		HttpSession session = request.getSession();
		EmployeeProject ep = (EmployeeProject) session.getAttribute(Const.EMPLOYEEPROJECT_IN_SESSION);
		
		String contactid = request.getParameter("id");
		
		
		ContactNote contactNote = new ContactNote();
		
		contactNote.setContactid(contactid);
		contactNote.setContent(content);
		contactNote.setCreatetime(DateUtil.getNow());
		contactNote.setId(PKUtil.getPK());
		contactNote.setEmployeeid(ep.getEmployeeid());
		
		new ContactNoteSevice().saveContactNote(contactNote);
		
		response.sendRedirect("contactnote.jspx?contactid="+contactid);
	}

	private void showEditContactNote(HttpServletRequest request,HttpServletResponse response) 
		throws ServletException, IOException{
		String id = request.getParameter("id");
		
		Contact contactInfo = new ContactService().findContact(id);
		
		HttpSession session = request.getSession();
		session.setAttribute("contactInfo", contactInfo);
		
		request.getRequestDispatcher("WEB-INF/views/contact_note.jsp").forward(request, response);

	}
}
